package com.lfs.market.controller.temp;

import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lfs
 * @date 2025/7/1 23:09:05
 * todo 删除时还有mapper下的mapper
 */
@RestController
@RequestMapping("/temp")
@Slf4j
public class TempController {
    @Autowired
    private BusiEquiMainMstNewService busiEquiMainMstNewService;

    @Autowired
    private RemoteBusiEquiMainMstNewService remoteBusiEquiMainMstNewService;
    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 甲方虚拟接口
     *
     * @return
     * @throws IOException
     */
    @PostMapping("/data")
    public AssetResponse getData() throws IOException {
        // 加载 resources 下的 data.json 文件
        ClassPathResource resource = new ClassPathResource("response.json");
        InputStream inputStream = resource.getInputStream();
        // 反序列化为 AssetResponse 对象
        return objectMapper.readValue(inputStream,
                new TypeReference<AssetResponse>() {
                });
    }

    /**
     * 自己调用的接口
     *
     * @return
     * @throws JsonProcessingException
     */
    @PostMapping("getData")
    public void callApi(@RequestParam int page, @RequestParam int limit) throws JsonProcessingException {
        String baseUrl = "http://localhost:5050/temp/test1";
        // 因为这个请求是模拟远程请求，在这里limit就得为200，因为pageSize为200，小于200数据会少于远程库中数据
        int pageSize = 200;

        String url = baseUrl +
                "?page=" + page +
                "&limit=" + limit;
        String body = HttpRequest.post(url).execute().body();
        try {
            AssetResponse<List<RemoteBusiEquiMainMstNew>> resultList = objectMapper.readValue(
                    body,
                    new TypeReference<AssetResponse<List<RemoteBusiEquiMainMstNew>>>() {
                    }
            );
            long count = resultList.getCount();
            long totalPages = (count + pageSize - 1) / pageSize;
            log.info("远程设备台账共有{}条数据", count);
            log.info("总共需要请求{}页", totalPages);
            List<BusiEquiMainMstNewEntity> localList = busiEquiMainMstNewService.list();
            List<RemoteBusiEquiMainMstNew> remoteList = resultList.getData();

            //根据远程数据和本地数据，对比后保存到本地数据库
            saveEquiList(localList, remoteList);

            // 请求剩余的页码
            for (int page2 = 2; page2 <= totalPages; page2++) {
                String url2 = baseUrl +
                        "?page=" + page2 +
                        "&limit=" + limit;
                String body2 = HttpRequest.post(url2).execute().body();
                AssetResponse<List<RemoteBusiEquiMainMstNew>> list = objectMapper.readValue(
                        body2,
                        new TypeReference<AssetResponse<List<RemoteBusiEquiMainMstNew>>>() {
                        }
                );
                List<RemoteBusiEquiMainMstNew> currentPageData = list.getData();
                saveEquiList(localList, currentPageData);
            }
        } catch (JsonProcessingException e) {
            log.error("同步远程设备台账数据出错", e);
            e.printStackTrace();
        }
    }

    /**
     * 根据本地数据与远程数据进行对比，对比之后保存增量数据
     *
     * @param localList
     * @param remoteList
     */
    private void saveEquiList(List<BusiEquiMainMstNewEntity> localList, List<RemoteBusiEquiMainMstNew> remoteList) {
        Map<String, BusiEquiMainMstNewEntity> localDataMap = localList.stream()
                .collect(Collectors.toMap(BusiEquiMainMstNewEntity::getEquiId, d -> d));
        Map<String, RemoteBusiEquiMainMstNew> remoteDataMap = remoteList.stream()
                .collect(Collectors.toMap(RemoteBusiEquiMainMstNew::getEquiId, d -> d));
        List<BusiEquiMainMstNewEntity> insertList = new ArrayList<>();
        for (Map.Entry<String, RemoteBusiEquiMainMstNew> entry : remoteDataMap.entrySet()) {
            String id = entry.getKey();
            RemoteBusiEquiMainMstNew data = entry.getValue();
            BusiEquiMainMstNewEntity busiEquiMainMstNewEntity = new BusiEquiMainMstNewEntity();
            if (!localDataMap.containsKey(id)) {
                busiEquiMainMstNewEntity.setEquiId(data.getEquiId());
                busiEquiMainMstNewEntity.setEquiCode(data.getEquiCode());
                busiEquiMainMstNewEntity.setEquiName(data.getEquiName());
//                busiEquiMainMstNewEntity.setTypeDefClassId(data.getTypeDefClassId() + data.gets().toLowerCase());
                busiEquiMainMstNewEntity.setTypeDefClassName(data.getTypeDefClassName());
                busiEquiMainMstNewEntity.setTypeDefGroupId(data.getTypeDefGroupId());
                busiEquiMainMstNewEntity.setTypeDefGroupName(data.getTypeDefGroupName());
                busiEquiMainMstNewEntity.setTypeDefTypeId(data.getTypeDefTypeId());
                busiEquiMainMstNewEntity.setTypeDefTypeName(data.getTypeDefTypeName());
                busiEquiMainMstNewEntity.setTypeDefModelId(data.getTypeDefModelId());
                busiEquiMainMstNewEntity.setTypeDefModelName(data.getTypeDefModelName());
//                busiEquiMainMstNewEntity.setConfigId();
//                busiEquiMainMstNewEntity.setConfig(data.getSpecifications());
                busiEquiMainMstNewEntity.setProduceNo(data.getProduceNo());
                busiEquiMainMstNewEntity.setFactory(data.getFactory());
                busiEquiMainMstNewEntity.setFactoryDate(data.getFactoryDate());
//                busiEquiMainMstNewEntity.setBuyDate();
//                busiEquiMainMstNewEntity.setTypeDefFullName();
//                busiEquiMainMstNewEntity.setOwnerType();
//                busiEquiMainMstNewEntity.setDataState();
//                busiEquiMainMstNewEntity.setEquiState();
//                busiEquiMainMstNewEntity.setTaskSteps();
//                busiEquiMainMstNewEntity.setPlateCode();
//                busiEquiMainMstNewEntity.setBaoshenCode();
//                busiEquiMainMstNewEntity.setUseAdress();
//                busiEquiMainMstNewEntity.setInDate();
//                busiEquiMainMstNewEntity.setInPlanDate();
//                busiEquiMainMstNewEntity.setInEquiType();
//                busiEquiMainMstNewEntity.setInEquiResult();
//                busiEquiMainMstNewEntity.setOutPlanDate();
//                busiEquiMainMstNewEntity.setOutDate();
//                busiEquiMainMstNewEntity.setOutEquiType();
//                busiEquiMainMstNewEntity.setDisposalDescription();
//                busiEquiMainMstNewEntity.setOutEquiResult();
//                busiEquiMainMstNewEntity.setMemo();
//                busiEquiMainMstNewEntity.setOwnerCompanyId();
//                busiEquiMainMstNewEntity.setOwnerCompanyName();
//                busiEquiMainMstNewEntity.setStartDate();
//                busiEquiMainMstNewEntity.setCreateUser();
//                busiEquiMainMstNewEntity.setCreateDate();
//                busiEquiMainMstNewEntity.setUpdateUser();
//                busiEquiMainMstNewEntity.setEndDate();
                busiEquiMainMstNewEntity.setCompanyId("2");

//                busiEquiMainMstNewEntity.setCompanyName();
//                busiEquiMainMstNewEntity.setCreateUserName();
//                busiEquiMainMstNewEntity.setUpdateUserName();
//                busiEquiMainMstNewEntity.setMngUserId();
//                busiEquiMainMstNewEntity.setMngUserName();
                busiEquiMainMstNewEntity.setTenantId("2");
//                busiEquiMainMstNewEntity.setIsInitError();
//                busiEquiMainMstNewEntity.setErrorInfo();
//                busiEquiMainMstNewEntity.setUserCode();
//                busiEquiMainMstNewEntity.setNengli();
//                busiEquiMainMstNewEntity.setGongfangCompanyId();
//                busiEquiMainMstNewEntity.setGongfangCompanyName();
//                busiEquiMainMstNewEntity.setCheckDate();
//                busiEquiMainMstNewEntity.setJingzhi();
//                busiEquiMainMstNewEntity.setRuzhangDate();
//                busiEquiMainMstNewEntity.setZhejiuYear();
//                busiEquiMainMstNewEntity.setZhejiuwanDate();
//                busiEquiMainMstNewEntity.setDengjizheng();
//                busiEquiMainMstNewEntity.setDengjiDate();
//                busiEquiMainMstNewEntity.setDengjizhengUnit();
//                busiEquiMainMstNewEntity.setJianyanReportCode();
//                busiEquiMainMstNewEntity.setEquiCode2();
//                busiEquiMainMstNewEntity.setHefaUnit();
//                busiEquiMainMstNewEntity.setHefaDate();
//                busiEquiMainMstNewEntity.setIsSupervise();
//                busiEquiMainMstNewEntity.setDaoqiDate();
//                busiEquiMainMstNewEntity.setChizhengType();
//                busiEquiMainMstNewEntity.setFazhengUnit();
//                busiEquiMainMstNewEntity.setZhengshuYouxiaoqiDate();
//                busiEquiMainMstNewEntity.setBaoxianDate();
//                busiEquiMainMstNewEntity.setEquiUseFlow();
                insertList.add(busiEquiMainMstNewEntity);
            }
        }
        if (!insertList.isEmpty()) {
            log.info("准备插入 {} 条新数据", insertList.size());
            busiEquiMainMstNewService.insertEquiBatch(insertList);
        }
    }

    /**
     * 测试用
     *
     * @return
     * @throws JsonProcessingException
     */
    @PostMapping("testData")
    public void testData() throws Exception {
//        BusiEquiMainMstNewEntity entity = busiEquiMainMstNewService.getById("000cbb01-86ff-48ac-9ac0-0b8631487e36");
        BusiEquiMainMstNewEntity entity = new BusiEquiMainMstNewEntity();
        entity.setEquiCode("2112");
        busiEquiMainMstNewService.save(entity);
        log.info("{}", entity);
    }

    /**
     * @return
     * @throws JsonProcessingException
     */
    @PostMapping("test1")
    public AssetResponse testData(@RequestParam int page, @RequestParam int limit) throws Exception {
        if (page < 0 || limit < 1) {
            throw new IllegalArgumentException("Page and limit must be valid numbers");
        }
        Page<RemoteBusiEquiMainMstNew> pageSize = new Page<>(page, limit);
        Page<RemoteBusiEquiMainMstNew> page1 = remoteBusiEquiMainMstNewService.page(pageSize, null);
        AssetResponse assetResponse = new AssetResponse(
                page1.getRecords(),
                page1.getTotal(),
                page1.getPages(),
                null // 可扩展字段
        );
        log.info("{}", assetResponse.getData());
        return assetResponse;
    }
}
